<template>
  <div class="bundle">
    <div class="search-box">
      <Form inline :label-width="80">
        <FormItem label="ID">
          <Input type="text" v-model="id" placeholder="ID">
          </Input>
        </FormItem>
        <FormItem label="检索条件">
          <Select v-model="paramName" style="width:100px" clearable>
            <Option value="itemCode">项目编码</Option>
            <Option value="itemName">项目名称</Option>
          </Select>
          <Input type="text" v-model="value" placeholder="" style="width:200px">
          </Input>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="doSearch">搜索</Button>
          <Button type="warning" @click="historySearch">历史版本</Button>
        </FormItem>
      </Form>
    </div>
    <div class="opt">
      <Button type="primary" @click="doSearch">刷新</Button>
      <Button type="success" @click="add">新增</Button>
    </div>
    <div class="data-table">
      <Table border :columns="columns" :data="tableData" size="small" :loading="tableLoading"></Table>
    </div>

    <Drawer
      :title="title"
      v-model="showEdit"
      width="720"
      :mask-closable="false"
      :styles="styles"
    >
      <Form :model="editData" :label-width="80">
        <FormItem label="文档号" prop="identifier">
          <Input v-model="editData.identifier"/>
        </FormItem>
        <FormItem label="文档类型" prop="docTypeCode">
          <CommonSelect v-model="editData.docTypeCode" :code.sync="editData.docTypeCode"
                        :name.sync="editData.docTypeName" :data-options="docTypeDict">
          </CommonSelect>
        </FormItem>
        <FormItem label="文档名称" prop="docTitle">
          <Input v-model="editData.docTitle"/>
        </FormItem>
        <FormItem label="文档作者" prop="author">
          <Input v-model="editData.author"/>
        </FormItem>
        <FormItem label="患者" prop="patientName">
          <Input v-model="editData.patientName"/>
        </FormItem>
        <FormItem label="性别" prop="sex">
          <Select v-model="editData.sex">
            <Option value="male">男</Option>
            <Option value="female">女</Option>
            <Option value="other">其他</Option>
            <Option value="unknown">未知</Option>
          </Select>
        </FormItem>
        <FormItem label="电话" prop="telephone">
          <Input v-model="editData.telephone"/>
        </FormItem>
        <FormItem label="出生日期" prop="birthDate">
          <DatePicker type="date" v-model="editData.birthDate"/>
        </FormItem>
        <FormItem label="家庭地址" prop="homeAddr">
          <Input v-model="editData.homeAddr"/>
        </FormItem>
        <FormItem label="就诊类型" prop="visitTypeCode">
          <CommonSelect v-model="editData.visitTypeCode" :code.sync="editData.visitTypeCode"
                        :name.sync="editData.visitTypeName" :data-options="visitTypeDict">
          </CommonSelect>
        </FormItem>
        <FormItem label="入院时间" prop="visitTime">
          <DatePicker type="datetime" v-model="editData.visitTime"/>
        </FormItem>
        <FormItem label="出院时间" prop="dischargeTime">
          <DatePicker type="datetime" v-model="editData.dischargeTime"/>
        </FormItem>
        <FormItem label="报告名称" prop="text">
          <Input v-model="editData.text"/>
        </FormItem>
        <FormItem label="检验项目" prop="code">
          <CommonSelect v-model="editData.code" :code.sync="editData.code"
                        :name.sync="editData.display" :data-options="labItemDict">
          </CommonSelect>
        </FormItem>
        <FormItem label="标本" prop="sample">
          <Input v-model="editData.sample"/>
        </FormItem>
        <FormItem label="检验/检查者" prop="tester">
          <Input v-model="editData.tester"/>
        </FormItem>
  <!--      <FormItem label="审核者" prop="reviwer">
          <Input v-model="editData.reviwer"/>
        </FormItem>-->
        <FormItem label="结果" prop="subItem" v-if="editData.docTypeName=='检验报告' && editData.subItem">
          <Button type="success" @click="editResult=true">编辑结果</Button>

          <labSubItem :row="editData.subItem" style="margin-top: 10px" :is-edit="editResult"></labSubItem>
        </FormItem>
      </Form>

      <div class="demo-drawer-footer">
        <Button style="margin-right: 8px" type="primary" @click="onSubmit">确定</Button>
        <Button type="error" @click="showEdit = false">取消</Button>
      </div>
    </Drawer>
  </div>
</template>

<script>
  import CommonSelect from "../../../components/select/commonSelect";
  import labSubItem from "../labreport/labSubItem"

  export default {
    name: "bundle",
    components: {labSubItem, CommonSelect},
    computed: {
      tableData() {
        let jData = [];

        this.$store.state.bundle.bundleList.forEach((entry, i) => {
          debugger;
          let re = entry.resource;
          if (re.total && re.total.myStringValue == '0' &&  re.hasOwnProperty('entry'))
            return;

          let
            docTypeCode,
            docTypeName,
            docTitle,
            code,
            display,
            text,
            sample,
            patientName,
            birthDate,
            telephone,
            homeAddr,
            sex,
            visitTypeCode,
            visitTypeName,
            visitTime,
            dischargeTime,
            tester,
            reviwer,
            author;

          let resUrl = re.id.myStringValue;
          let id = re.id.myUnqualifiedId;
          let versionId = re.meta.versionId ? re.meta.versionId.myStringValue : "";
          let identifier = (re.identifier && re.identifier.value) ? re.identifier.value.myStringValue : "";

          let subItem = [];
          let subId = 0;


          if(!re.entry){

            return;
          }
          re.entry.forEach(o => {
            if (o.request) {
              let type = o.request.url.myStringValue;
              let res = o.resource;
              switch (type) {
                case "Composition":
                  author = (res.author && res.author[0].display) ? res.author[0].display.myStringValue : "";
                  docTitle = res.title ? res.title.myStringValue : '';
                  docTypeCode = (res.type && res.type.coding && res.type.coding[0].code) ?
                    res.type.coding[0].code.myStringValue : "";
                  docTypeName = (res.type && res.type.text) ? res.type.text.myStringValue : "";
                  break;
                case "Patient":
                  patientName = (res.name && res.name[0].text) ? res.name[0].text.myStringValue : "";
                  telephone = (res.telecom && res.telecom[0].value) ? res.telecom[0].value.myStringValue : "";
                  sex = res.gender ? res.gender.myStringValue : "";
                  birthDate = res.birthDate ? res.birthDate.myStringValue : "";
                  homeAddr = (res.address && res.address[0].line) ? res.address[0].line[0].myStringValue : "";
                  break;
                case "Encounter":
                  visitTypeCode = res.class_ ? (res.class_.code ? res.class_.code.myStringValue : '') : '';
                  visitTypeName = res.class_ ? (res.class_.display ? res.class_.display.myStringValue : '') : '';
                  visitTime = res.period ? (res.period.start ? res.period.start.myStringValue : '') : '';
                  dischargeTime = res.period ? (res.period.end ? res.period.end.myStringValue : '') : '';
                  break;
                case "Observation":

                    if (res.value) {
                      let sub = {};
                      sub.no = ++subId;

                      tester = res.performer && res.performer[0].display ? res.performer[0].display.myStringValue : '';

                      sub.code = (res.code && res.code.coding && res.code.coding[0]) ? res.code.coding[0].code.myStringValue : "";
                      sub.display = (res.code && res.code.text) ? res.code.text.myStringValue : "";
                      sub.value = (res.value && res.value.value) ? res.value.value.myStringValue : "";
                      sub.unit = (res.value && res.value.unit) ? res.value.unit.myStringValue : "";
                      sub.low = (res.referenceRange && res.referenceRange[0].low && res.referenceRange[0].low.value) ? res.referenceRange[0].low.value.myStringValue : "";
                      sub.high = (res.referenceRange && res.referenceRange[0].high && res.referenceRange[0].high.value) ? res.referenceRange[0].high.value.myStringValue : "";

                      subItem.push(sub);
                    } else {
                      debugger;
                      code = (res.code && res.code.coding && res.code.coding[0]) ? res.code.coding[0].code.myStringValue : "";
                      display = (res.code && res.code.coding && res.code.coding[0]) ? res.code.coding[0].display.myStringValue : "";
                      text = (res.code && res.code.text) ? res.code.text.myStringValue : "";
                      sample=(res.specimen &&  res.specimen.display) ? res.specimen.display.myStringValue:"";
                    }


                  break;

              }
            } else if (o.fullUrl) {
           debugger;
              let res = o.resource;
              let exp = new RegExp(this.$store.state.base.fhirServer + '(\\S*)' + '/');

            //  let type = o.fullUrl.myStringValue.match(exp)[1].replace("/", "");
              let type =(o.fullUrl.myStringValue.match(exp)) ?  o.fullUrl.myStringValue.match(exp)[1].replace("/", ""):"";

              if(!type){
                exp = new RegExp('http://www.hl7.org.cn/open' + '(\\S*)' + '/');
                type =(o.fullUrl.myStringValue.match(exp)) ?  o.fullUrl.myStringValue.match(exp)[1].replace("/", ""):"";
              }

              switch (type) {
                case "Composition":
                  author = (res.author && res.author[0].display) ? res.author[0].display.myStringValue : "";
                  docTitle = res.title ? res.title.myStringValue : '';
                  docTypeCode = (res.type && res.type.coding && res.type.coding[0].code) ?
                    res.type.coding[0].code.myStringValue : "";
                  docTypeName = (res.type && res.type.text) ? res.type.text.myStringValue : "";
                  break;
                case "Patient":
                  patientName = (res.name && res.name[0].text) ? res.name[0].text.myStringValue : "";
                  telephone = (res.telecom && res.telecom[0].value) ? res.telecom[0].value.myStringValue : "";
                  sex = res.gender ? res.gender.myStringValue : "";
                  birthDate = res.birthDate ? res.birthDate.myStringValue : "";
                  homeAddr = (res.address && res.address[0].line) ? res.address[0].line[0].myStringValue : "";
                  break;
                case "Encounter":
                  visitTypeCode = res.class_ ? (res.class_.code ? res.class_.code.myStringValue : '') : '';
                  visitTypeName = res.class_ ? (res.class_.display ? res.class_.display.myStringValue : '') : '';
                  visitTime = res.period ? (res.period.start ? res.period.start.myStringValue : '') : '';
                  dischargeTime = res.period ? (res.period.end ? res.period.end.myStringValue : '') : '';
                  break;
                case "Observation":

                    if (res.value) {
                      let sub = {};
                      sub.no = ++subId;

                      tester = res.performer && res.performer[0].display ? res.performer[0].display.myStringValue : '';

                      sub.code = (res.code && res.code.coding && res.code.coding[0]) ? res.code.coding[0].code.myStringValue : "";
                      sub.display = (res.code && res.code.text) ? res.code.text.myStringValue : "";
                      sub.value = (res.value && res.value.value) ? res.value.value.myStringValue : "";
                      sub.unit = (res.value && res.value.unit) ? res.value.unit.myStringValue : "";
                      sub.low = (res.referenceRange && res.referenceRange[0].low && res.referenceRange[0].low.value) ? res.referenceRange[0].low.value.myStringValue : "";
                      sub.high = (res.referenceRange && res.referenceRange[0].high && res.referenceRange[0].high.value) ? res.referenceRange[0].high.value.myStringValue : "";

                      subItem.push(sub);
                    } else {
                      code = (res.code && res.code.coding && res.code.coding[0]) ? res.code.coding[0].code.myStringValue : "";
                      display = (res.code && res.code.coding && res.code.coding[0]) ? res.code.coding[0].display.myStringValue : "";
                      text = (res.code && res.code.text) ? res.code.text.myStringValue : "";
                      sample=(res.specimen &&  res.specimen.reference) ? res.specimen.reference.myStringValue:"";
                    }

                  break;

              }
            } else {
              debugger;
              let res = o.resource;
              let type = o.formatCommentsPre ? o.formatCommentsPre[0] : (res.formatCommentsPre ? res.formatCommentsPre[0] : "");

              switch (type.replace(/\s/g, "")) {
                case "TheCompositionresource":
                  author = (res.author && res.author[0].display) ? res.author[0].display.myStringValue : "";
                  docTitle = res.title ? res.title.myStringValue : '';
                  docTypeCode = (res.type && res.type.coding && res.type.coding[0].code) ?
                    res.type.coding[0].code.myStringValue : "";
                  docTypeName = (res.type && res.type.text) ? res.type.text.myStringValue : "";
                  break;
                case "患者信息":
                  patientName = (res.name && res.name[0].text) ? res.name[0].text.myStringValue : "";
                  telephone = (res.telecom && res.telecom[0].value) ? res.telecom[0].value.myStringValue : "";
                  sex = res.gender ? res.gender.myStringValue : "";
                  birthDate = res.birthDate ? res.birthDate.myStringValue : "";
                  homeAddr = (res.address && res.address[0].line) ? res.address[0].line[0].myStringValue : "";
                  break;
                case "关联就诊信息":
                  break;
                case "检验结果":

                    if (res.value) {
                      let sub = {};
                      sub.no = ++subId;

                      tester = res.performer && res.performer[0].display ? res.performer[0].display.myStringValue : '';

                      sub.code = (res.code && res.code.coding && res.code.coding[0]) ? res.code.coding[0].code.myStringValue : "";
                      sub.display = (res.code && res.code.text) ? res.code.text.myStringValue : "";
                      sub.value = (res.value && res.value.value) ? res.value.value.myStringValue : "";
                      sub.unit = (res.value && res.value.unit) ? res.value.unit.myStringValue : "";
                      sub.low = (res.referenceRange && res.referenceRange[0].low && res.referenceRange[0].low.value) ? res.referenceRange[0].low.value.myStringValue : "";
                      sub.high = (res.referenceRange && res.referenceRange[0].high && res.referenceRange[0].high.value) ? res.referenceRange[0].high.value.myStringValue : "";

                      subItem.push(sub);
                    } else {
                      code = (res.code && res.code.coding && res.code.coding[0]) ? res.code.coding[0].code.myStringValue : "";
                      display = (res.code && res.code.coding && res.code.coding[0]) ? res.code.coding[0].display.myStringValue : "";
                      text = (res.code && res.code.text) ? res.code.text.myStringValue : "";
                      sample=(res.specimen &&  res.specimen.reference) ? res.specimen.reference.myStringValue:"";
                    }


                  break;

              }
            }
          });
          jData.push({
            url: resUrl,
            id: id,
            versionId: versionId,
            identifier: identifier,
            docTypeCode: docTypeCode,
            docTypeName: docTypeName,
            docTitle: docTitle,
            code: code,
            display: display,
            text: text,
            sample: sample,
            patientName: patientName,
            birthDate: birthDate,
            telephone: telephone,
            homeAddr: homeAddr,
            sex: sex,
            visitTypeCode: visitTypeCode,
            visitTypeName: visitTypeName,
            visitTime: visitTime,
            dischargeTime: dischargeTime,
            tester: tester,
            reviwer: reviwer,
            author: author,
            subItem: subItem
          })

        });
        return jData;
      }
    },
    data() {
      return {
        type: 'Bundle',
        SEQ: 0,
        id: null,
        paramName: null,
        value: null,
        tableLoading: false,
        showEdit: false,
        isUpdate: false,
        title: '',
        editData: {},
        visitTypeDict: [{code: 'IMP', name: '住院'}],
        docTypeDict: [{code: '28655-1', name: '检查报告'}, {code: '28655-2', name: '检验报告'}],
        labItemDict: [{code: '58410-2', name: '血常规'}],
        editResult: true,
        styles: {
          height: 'calc(100% - 55px)',
          overflow: 'auto',
          paddingBottom: '53px',
          position: 'static'
        },
        columns: [
          {
            type: 'expand',
            width: 50,
            render: (h, params) => {

                return h(labSubItem, {
                  props: {
                    row: params.row.subItem,
                    isEdit: false
                  }
                })
              }

          },
          {
            title: 'ID',
            key: 'id'
          },
          {
            title: '版本',
            key: 'versionId'
          },
          {
            title: '文档号',
            key: 'identifier'
          },
          {
            title: '文档类型名称',
            key: 'docTypeName'
          },
          {
            title: '文档名称',
            key: 'docTitle'
          },
          {
            title: '文档作者',
            key: 'author'
          },
          {
            title: '患者',
            key: 'patientName'
          },
          {
            title: '就诊类型',
            key: 'visitTypeName'
          },
          {
            title: '就诊（入院）时间',
            key: 'visitTime'
          },
          {
            title: '出院时间',
            key: 'dischargeTime'
          },
          {
            title: '项目代码',
            key: 'code'
          },
          {
            title: '项目名称',
            key: 'display'
          },
          {
            title: '报告名称',
            key: 'text'
          },
          {
            title: '检验/检查者',
            key: 'tester'
          },
          /*{
            title: '审核者',
            key: 'reviwer'
          },*/
          {
            title: "操作",
            width: 120,
            type: "render",
            render: (h, params) => {
              return h('div', {
                class: 'btn-wrap'
              }, [
                h('a', {
                  on: {
                    click: () => {
                      this.update(params.row)
                    }
                  }
                }, '编辑'),
                h('Divider', {
                  props: {type: 'vertical'},
                }),
                h('a', {
                  on: {
                    click: () => {
                      this.remove(params.row)
                    }
                  }
                }, '删除'),
              ])
            }
          }
        ]
      }
    },
    created() {
      this.doSearch();
    },
    methods: {
      changeItem(item) {
        console.log(item);
      },
      doSearch() {

        this.tableLoading = true;
        this.$store.dispatch('getBundleList', {
          type: this.type,
          id: this.id,
          paramName: this.paramName,
          value: this.value,
        }).then(() => {
          this.tableLoading = false;
        }).catch(res => {
          this.$Notice.error({
            title: re.error,
            desc: re.message
          });
          this.tableLoading = false;
        })
      },
      historySearch() {
        if (!this.id) {
          this.$Message.error('请输入ID');
          return;
        }
        this.tableLoading = true;
        this.$store.dispatch('getHistoryBundleList', {
          type: this.type,
          id: this.id,
        }).then(() => {
          this.tableLoading = false;
        })
      },
      add() {
        this.editData = {
          identifier: "doc_100000" + (++this.SEQ),
          docTypeCode: '28655-1',
          docTypeName: '检验报告',
          docTitle: '检验报告',
          code: "58410-2",
          display: "血常规",
          text: "血常规报告",
          sample: "血清",
          patientName: '张三',
          birthDate: "2003-01-12",
          telephone: "13800138000",
          homeAddr: "北京市东城区景山前街4号",
          sex: "male",
          visitTypeCode: 'IMP',
          visitTypeName: '住院',
          visitTime: '2018-10-28 12:46:41',
          dischargeTime: '2018-11-01 12:46:48',
          tester: "李四",
          reviwer: "王五",
          author: '宋健',
          subItem: [
            {
              no: "1",
              code: "718-7",
              display: "血红蛋白",
              value: "",
              unit: "g/L",
              low: "135.0",
              high: "180.0"
            },
            {
              no: "2",
              code: "789-8",
              display: "红细胞计数",
              value: "",
              unit: "x10*12/L",
              low: "4.2",
              high: "6.2"
            },
            {
              no: "3",
              code: "777-3",
              display: "血小板计数",
              value: "",
              unit: "x10*9/L",
              low: "150",
              high: "450"
            },
            {
              no: "4",
              code: "2028-9",
              display: "红细胞压积",
              value: "",
              unit: "%",
              low: "38",
              high: "52"
            }, {
              no: "5",
              code: "787-2",
              display: "红细胞平均体积",
              value: "",
              unit: "fL",
              low: "80",
              high: "98"
            },
            {
              no: "6",
              code: "6690-2",
              display: "白细胞计数",
              value: "",
              unit: "x10*9/L",
              low: "4",
              high: "11"
            }
          ]
        };
        this.showEdit = true;
        this.isUpdate = false;
        this.title = '新增检验报告';
      },
      update(row) {
        this.editData = JSON.parse(JSON.stringify(row));
        this.showEdit = true;
        this.isUpdate = true;
        this.title = '更新检验报告';
      },
      remove(row) {
        this.$store.dispatch('deleteBundle', {
          type: this.type,
          id: row.id
        }).then(() => {
          this.$Message.success('删除成功');
          this.id = row.id;
          this.doSearch();
        });
      },
      onSubmit() {
        if (this.isUpdate) {
          this.$store.dispatch('updateBundle', Object.assign({type: this.type}, this.editData)).then(() => {
            this.$Message.success('更新成功');
            this.showEdit = false;
            this.id = this.editData.id;
            this.doSearch();
          });
        } else {
          this.$store.dispatch('createBundle', Object.assign({type: this.type}, this.editData)).then((res) => {
            this.$Message.success('新增成功');
            this.showEdit = false;
            this.id = res.data.myId.myUnqualifiedId;
            this.doSearch();
          });
        }
      }
    }
  }
</script>

<style scoped>
  .data-table {
    margin-top: 10px;
  }

  .demo-drawer-footer {
    width: 100%;
    position: absolute;
    bottom: 0;
    left: 0;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    background: #fff;
  }
</style>
